package array;

import org.junit.Test;

import java.util.List;

/**
 * @author way
 * @create 2024-12-03 10:15 https://leetcode.cn/problems/binary-search/
 */
public class _704_search {
    public int search(int[] nums, int target) {
        for (int i = 0; i < nums.length; i++) {
            if (nums[i] == target) return i;
        }

        return -1;
    }

    public int search_two(int[] nums, int target) {
        int left = 0;
        int right = nums.length - 1;

        while (left <= right) {
            //int mid = (left+right)/2 防止数据直接相加产生溢出。
            int mid = left + (right - left) / 2;

            if (nums[mid] == target) return mid;
            else if (nums[mid] > target) right = mid - 1;
            else if (nums[mid] < target) left = mid + 1;
        }

        return -1;
    }

    @Test
    public void test() {
        int[] nums = {-1, 0, 3, 5, 9, 12};
        int target = 9;
        System.out.println(search(nums, target));
        System.out.println(search_two(nums, target));
    }
}
